package com.enfi.api.modules.bz.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.enfi.api.domain.res.ApiResult;
import com.enfi.api.modules.bz.domain.bpm.ResDTO;
import com.enfi.api.modules.bz.domain.bpm.ResListDTO;
import com.enfi.api.modules.bz.domain.bpm.UserGroupBpm;
import com.enfi.api.modules.bz.domain.bpm.detail.Detail;
import com.enfi.api.modules.bz.domain.bpm.history.HistoryRow;
import com.enfi.api.modules.bz.domain.bpm.instance.Instance;
import com.enfi.api.modules.bz.domain.bpm.instance.InstanceRow;
import com.enfi.api.modules.bz.domain.bpm.instance.TaskPerson;
import com.enfi.api.modules.bz.domain.bpm.instance.TaskPersonHandler;
import com.enfi.api.modules.bz.domain.bpm.task.Task;
import com.enfi.api.modules.bz.domain.bpm.task.TaskRow;
import com.enfi.api.modules.bz.service.FlowService;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping({"flow"})
public class FlowController {
    @Autowired
    private FlowService flowService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 创建工单
     */
    @PostMapping("createOrder")
    public String createOrder(@RequestParam Map map){
        return flowService.createOrder(map);
    }

    /**
     * 列表
     * @param map
     */
    @PostMapping("list")
    public Object  list(@RequestBody Map map){
        String state=(String)map.getOrDefault("state","todo");
        if("todo".equalsIgnoreCase(state)){
            if(map.containsKey("startTimeFrom")){
                map.put("createTimeFrom",map.get("startTimeFrom"));
            }
            if(map.containsKey("startTimeTo")){
                map.put("createTimeTo",map.get("startTimeTo"));
            }
            ResDTO<Task> resDTO= JSON.parseObject(flowService.taskList(map)).toJavaObject(new TypeReference<ResDTO<Task>>(){});
            ApiResult apiResult=ApiResult.custom(resDTO.getCode()==0,"",resDTO.getMessage());
            Task task=resDTO.getResponse();
            Instance instance=new Instance();
            instance.setTotal(task.getTotal());
            List<InstanceRow> rows= Lists.newArrayList();
            instance.setRows(rows);
            apiResult.add(instance);
            Optional.of(task.getRows()).ifPresent(v->{
                v.forEach(t->{
                    TaskRow taskRow=t;
                    InstanceRow instanceRow=new InstanceRow();
                    instanceRow.setTaskName(taskRow.getName());
                    instanceRow.setTaskDefinitionKey(taskRow.getTaskDefinitionKey());
                    instanceRow.setBusinessKey(taskRow.getProcessInstance()!=null?taskRow.getProcessInstance().getBusinessKey():"");
                    instanceRow.setState(taskRow.getProcessInstance()!=null?taskRow.getProcessInstance().getState():"");
                    instanceRow.setProcessDefinitionKey(taskRow.getProcessInstance()!=null?taskRow.getProcessInstance().getProcessDefinitionKey():"");
                    instanceRow.setProcessDefinitionName(taskRow.getProcessInstance()!=null?taskRow.getProcessInstance().getProcessDefinitionName():"");
                    instanceRow.setStartTime(taskRow.getCreated());
                    TaskPerson taskPerson=new TaskPerson();
                    TaskPersonHandler taskPersonHandler=new TaskPersonHandler();
                    taskPersonHandler.setUserId(taskRow.getAssignee());
                    taskPersonHandler.setGroupName("软件管理");
                    UserGroupBpm userGroupBpm=userGroupBpm(taskPersonHandler.getUserId());
                    taskPersonHandler.setGroupName(userGroupBpm.getUserGroup());
                    taskPersonHandler.setUserName(userGroupBpm.getUserName());
                    taskPerson.setHandler(Lists.newArrayList());
                    taskPerson.getHandler().add(taskPersonHandler);
                    taskPerson.setNode(instanceRow.getTaskName());
                    instanceRow.setTaskPersons(Lists.newArrayList());
                    instanceRow.getTaskPersons().add(taskPerson);
                    instanceRow.setEndTime(taskRow.getProcessInstance()!=null?taskRow.getProcessInstance().getEndTime():null);
                    instanceRow.setVariables(taskRow.getVariables());
                    instanceRow.setProcessInstanceId(taskRow.getProcessInstanceId());
                    instanceRow.setId(taskRow.getId());
                    rows.add(instanceRow);
                });
            });
            return apiResult;
        }else {
            ResDTO<Instance> resDTO= JSON.parseObject(flowService.list(map)).toJavaObject(new TypeReference<ResDTO<Instance>>(){});
            if(resDTO.getResponse()!=null&& resDTO.getResponse().getRows()!=null){
                resDTO.getResponse().getRows().forEach(v->{
                    if(v.getTaskPersons()!=null){
                        v.getTaskPersons().forEach(t->{
                            if(t.getHandler()!=null){
                                t.getHandler().forEach(p->{
                                    if(StringUtils.isNotBlank(p.getUserId())){
                                        p.setUserName("默认");
                                        p.setGroupName("默认");
                                        UserGroupBpm userGroupBpm=userGroupBpm(p.getUserId());
                                        p.setGroupName(userGroupBpm.getUserGroup());
                                        p.setUserName(userGroupBpm.getUserName());
                                    }
                                });
                            }

                        });
                    }
                });
            }
            return ApiResult.custom(resDTO.getCode()==0,"",resDTO.getMessage()).add(resDTO.getResponse());
        }

    }
    /**
     * 任务详情
     * @param map
     */
    @PostMapping("detail")
    public Object detail(@RequestBody Map map){
        ResDTO<Detail> resDTO= JSON.parseObject( flowService.detail(map)).toJavaObject(new TypeReference<ResDTO<Detail>>(){});
        ResListDTO<Map> assign= JSON.parseObject( flowService.getAssign(map)).toJavaObject(new TypeReference<ResListDTO<Map>>(){});
        if(resDTO.getCode()==0){
            resDTO.getResponse().setAssignees(assign.getResponse());
        }
        return ApiResult.custom(resDTO.getCode()==0,"",resDTO.getMessage()).add(resDTO.getResponse());
    }
    /**
     * 任务流转
     * @param map
     */
    @PostMapping("complete")
    public Object complete(@RequestBody Map map){
        String type=map.getOrDefault("type","").toString();
        if("transfer".equalsIgnoreCase(type)){
            ResDTO<Object> resDTO= JSON.parseObject( flowService.transfer(map)).toJavaObject(new TypeReference<ResDTO<Object>>(){});
            return ApiResult.custom(resDTO.getCode()==0,"",resDTO.getMessage());
        }else {
            ResDTO<Object> resDTO= JSON.parseObject( flowService.complete(map)).toJavaObject(new TypeReference<ResDTO<Object>>(){});
            return ApiResult.custom(resDTO.getCode()==0,"",resDTO.getMessage());
        }

    }

    @PostMapping("history")
    public Object history(@RequestBody Map map){
        ResListDTO<HistoryRow> resDTO= JSON.parseObject( flowService.history(map)).toJavaObject(new TypeReference<ResListDTO<HistoryRow>>(){});
        if(resDTO.getResponse()!=null){
            Iterator<HistoryRow> iterator = resDTO.getResponse().iterator();
            while(iterator.hasNext()){
                HistoryRow historyRow=iterator.next();
                if(StringUtils.isBlank(historyRow.getName())){
                    iterator.remove();
                    continue;
                }
                Map historyData=historyRow.getData();

                String creator_nm=historyData.getOrDefault("creator_nm","").toString();
                String creator_id=historyData.getOrDefault("creator_id","").toString();
                String complete_nm="";
                String complete_id="";
                String complete_group="";
                if(StringUtils.isNotBlank(creator_nm)){
                    complete_nm=creator_nm;
                    complete_id=creator_id;
                }else {
                    complete_nm=historyData.getOrDefault("complete_nm","").toString();
                    complete_id=historyData.getOrDefault("complete_id","").toString();
                }
                UserGroupBpm userGroupBpm=userGroupBpm(complete_id);
                complete_group=userGroupBpm.getUserGroup();
                String type="提交";
                Integer isCancel=Integer.valueOf(historyData.getOrDefault("isCancel",-1).toString());
                if(Integer.valueOf(1).equals(isCancel)){
                     type="申请作废";
                }
                Integer isRecover=Integer.valueOf(historyData.getOrDefault("isRecover",-1).toString());
                if(Integer.valueOf(0).equals(isRecover)){
                   type ="确认作废";
                }
                String czpizhu=historyData.getOrDefault("czpizhu","").toString();
                if(StringUtils.isNotBlank(czpizhu)){
                    if(String.valueOf("finish").equalsIgnoreCase(czpizhu)){
                        type="结束";
                    }else if(String.valueOf("ok").equalsIgnoreCase(czpizhu)){
                        type="提交";
                    }
                }
                //运营预处理
                String yystart=historyData.getOrDefault("yystart","").toString();
                if(StringUtils.isNotBlank(yystart)){
                    if(String.valueOf("finish").equalsIgnoreCase(yystart)){
                        type="结束";
                    }else if(String.valueOf("ok").equalsIgnoreCase(yystart)){
                        type="提交";
                    }
                }
                //部门主任预处理
                String qtbmpz=historyData.getOrDefault("qtbmpz","").toString();
                if(StringUtils.isNotBlank(qtbmpz)){
                    if(String.valueOf("finish").equalsIgnoreCase(qtbmpz)){
                        type="结束";
                    }else if(String.valueOf("ok").equalsIgnoreCase(qtbmpz)){
                        type="提交";
                    }
                }

                //部门处理人
                String bmstart=historyData.getOrDefault("bmstart","").toString();
                if(StringUtils.isNotBlank(bmstart)){
                    if(String.valueOf("finish").equalsIgnoreCase(bmstart)){
                        type="结束";
                    }else if(String.valueOf("ok").equalsIgnoreCase(bmstart)){
                        type="提交";
                    }
                }
                //部门主任审核
                String bmzrstart=historyData.getOrDefault("bmzrstart","").toString();
                if(StringUtils.isNotBlank(bmzrstart)){
                    if(String.valueOf("finish").equalsIgnoreCase(bmzrstart)){
                        type="结束";
                    }else if(String.valueOf("ok").equalsIgnoreCase(bmzrstart)){
                        type="提交";
                    }
                }

                //部门主管副总
                String zgfzstart=historyData.getOrDefault("zgfzstart","").toString();
                if(StringUtils.isNotBlank(zgfzstart)){
                    if(String.valueOf("finish").equalsIgnoreCase(zgfzstart)){
                        type="结束";
                    }else if(String.valueOf("ok").equalsIgnoreCase(zgfzstart)){
                        type="提交";
                    }
                }
                //总工程师
                String  zgcsstart=historyData.getOrDefault("zgcsstart","").toString();
                if(StringUtils.isNotBlank(zgcsstart)){
                    if(String.valueOf("finish").equalsIgnoreCase(zgcsstart)){
                        type="结束";
                    }else if(String.valueOf("ok").equalsIgnoreCase(zgcsstart)){
                        type="提交";
                    }
                }

                //实施
                String ssqrstart=historyData.getOrDefault("ssqrstart","").toString();
                if(StringUtils.isNotBlank(ssqrstart)){
                    if(String.valueOf("finish").equalsIgnoreCase(ssqrstart)){
                        type="结束";
                    }else if(String.valueOf("ok").equalsIgnoreCase(ssqrstart)){
                        type="提交";
                    }
                }
                historyData.put("complete_nm", complete_nm);
                historyData.put("type",type);
                historyData.put("complete_group",complete_group);
            }

        }
        return ApiResult.custom(resDTO.getCode()==0,"",resDTO.getMessage()).add(resDTO.getResponse());
    }
    /**
     * 任务挂起
     * @param map
     */
    @PostMapping("suspended")
    public Object suspended(@RequestParam Map map){
        ResDTO<Object> resDTO= JSON.parseObject( flowService.suspended(map)).toJavaObject(new TypeReference<ResDTO<Object>>(){});
        return ApiResult.custom(resDTO.getCode()==0,"",resDTO.getMessage());
    }

    public UserGroupBpm userGroupBpm(String userId){
        UserGroupBpm userGroupBpm=UserGroupBpm.builder().build();
        try {
            Map map1= jdbcTemplate.queryForMap("select  user_name,ref_code from js_sys_user where extend_s4=? limit 1",userId);
            String a=(String)map1.getOrDefault("user_name","");
            String b=(String)map1.getOrDefault("ref_code","");
            userGroupBpm.setUserName(a);
            if(StringUtils.isNotBlank(b)){
                Map map2=    jdbcTemplate.queryForMap("select full_name from js_sys_office where office_code " +
                        "=(select  office_code from js_sys_employee where emp_code=? )",b);
                userGroupBpm.setUserGroup(map2.getOrDefault("full_name","").toString());
            }
        }catch (Exception e){

        }
        return userGroupBpm;
    }
}
